import React, { useState, useEffect } from 'react';
import { Button } from './components/ui/button';
import { Badge } from './components/ui/badge';
import { Brain, Home, Flame, Star } from 'lucide-react';
import { ReactionTimeTest } from './components/ReactionTimeTest';
import { TypingSpeedTest } from './components/TypingSpeedTest';
import { MemoryTest } from './components/MemoryTest';
import { AttentionTest } from './components/AttentionTest';
import { CoordinationTest } from './components/CoordinationTest';
import { ColorTest } from './components/ColorTest';
import { MathTest } from './components/MathTest';
import { LogicalReasoningTest } from './components/LogicalReasoningTest';
import { VisualPerceptionTest } from './components/VisualPerceptionTest';
import { WorkingMemoryTest } from './components/WorkingMemoryTest';
import { SpatialReasoningTest } from './components/SpatialReasoningTest';
import { PatternRecognitionTest } from './components/PatternRecognitionTest';
import { AbstractReasoningTest } from './components/AbstractReasoningTest';
import { CriticalThinkingTest } from './components/CriticalThinkingTest';
import { CreativeThinkingTest } from './components/CreativeThinkingTest';
import { WordAssociationTest } from './components/WordAssociationTest';
import { AudioMemoryTest } from './components/AudioMemoryTest';
import { SequenceReasoningTest } from './components/SequenceReasoningTest';
import { EmotionRecognitionTest } from './components/EmotionRecognitionTest';
import { MultitaskTest } from './components/MultitaskTest';
import { ReadingComprehensionTest } from './components/ReadingComprehensionTest';
import { CognitiveFlexibilityTest } from './components/CognitiveFlexibilityTest';
import { InhibitoryControlTest } from './components/InhibitoryControlTest';
import { ProcessingSpeedTest } from './components/ProcessingSpeedTest';
import { SpatialMemoryTest } from './components/SpatialMemoryTest';
import { VerbalFluencyTest } from './components/VerbalFluencyTest';
import { DecisionMakingTest } from './components/DecisionMakingTest';
import { TimePerceptionTest } from './components/TimePerceptionTest';
import { DigitMemoryTest } from './components/DigitMemoryTest';
import { ConceptFormationTest } from './components/ConceptFormationTest';
import { Dashboard } from './components/Dashboard';
import { ProfilePage } from './components/ProfilePage';
import { HomePage } from './components/HomePage';
import { AIBattleMode } from './components/AIBattleMode';
import { LanguageSelector } from './components/LanguageSelector';
import { LanguageProvider, useLanguage } from './contexts/LanguageContext';
import { TestResult, UserProfile, Achievement, TestType } from './types';
import { tests, initialAchievements } from './constants/tests';
import { updateUserStats, checkAchievements, calculateStreakDays } from './utils/achievements';
import { motion } from 'motion/react';

function AppContent() {
  const { t } = useLanguage();
  const [currentView, setCurrentView] = useState<TestType | 'ai-battle'>('home');
  const [activeTab, setActiveTab] = useState<string>('tests');
  const [testResults, setTestResults] = useState<TestResult[]>([]);
  const [userProfile, setUserProfile] = useState<UserProfile>({
    name: t('user.test_user'),
    age: 25,
    level: 1,
    totalTests: 0,
    averageScore: 0,
    badges: [],
    streak: 0,
    joinDate: new Date()
  });
  const [achievements, setAchievements] = useState<Achievement[]>(initialAchievements);

  // Update user profile name when language changes
  useEffect(() => {
    setUserProfile(prev => ({ ...prev, name: t('user.test_user') }));
  }, [t]);

  // Calculate user stats and achievements
  useEffect(() => {
    const statsUpdate = updateUserStats(testResults);
    setUserProfile(prev => ({ ...prev, ...statsUpdate }));
    
    const updatedAchievements = checkAchievements(testResults, achievements);
    setAchievements(updatedAchievements);
  }, [testResults]);

  const handleTestComplete = (result: TestResult) => {
    const now = new Date();
    const enhancedResult: TestResult = {
      ...result,
      // 确保所有时间字段都被正确设置
      completedAt: result.completedAt || now,
      date: result.date || now,
      timestamp: result.timestamp || now,
      // 生成合理的百分位数
      percentile: Math.max(1, Math.min(99, Math.round(result.score + Math.random() * 20 - 10))),
      // 确保测试类型字段存在
      testType: result.testType
    };
    
    setTestResults(prev => [...prev, enhancedResult]);
    
    // 根据测试类型决定跳转的tab
    if (result.details?.battleMode) {
      // AI对战完成后跳转到AI对战tab
      setActiveTab('ai-battle');
    } else {
      // 普通测试完成后跳转到数据面板tab
      setActiveTab('dashboard');
    }
    setCurrentView('home');
  };

  const handleStartTest = (testType: TestType | 'ai-battle') => {
    if (testType === 'home') {
      setCurrentView('home');
      setActiveTab('tests');
    } else {
      setCurrentView(testType);
    }
  };

  const renderTestComponent = () => {
    switch (currentView) {
      case 'reaction':
        return <ReactionTimeTest onComplete={handleTestComplete} />;
      case 'typing':
        return <TypingSpeedTest onComplete={handleTestComplete} />;
      case 'memory':
        return <MemoryTest onComplete={handleTestComplete} />;
      case 'attention':
        return <AttentionTest onComplete={handleTestComplete} />;
      case 'coordination':
        return <CoordinationTest onComplete={handleTestComplete} />;
      case 'color':
        return <ColorTest onComplete={handleTestComplete} />;
      case 'math':
        return <MathTest onComplete={handleTestComplete} />;
      case 'logical':
        return <LogicalReasoningTest onComplete={handleTestComplete} />;
      case 'visual':
        return <VisualPerceptionTest onComplete={handleTestComplete} />;
      case 'working-memory':
        return <WorkingMemoryTest onComplete={handleTestComplete} />;
      case 'spatial-reasoning':
        return <SpatialReasoningTest onComplete={handleTestComplete} />;
      case 'pattern-recognition':
        return <PatternRecognitionTest onComplete={handleTestComplete} />;
      case 'abstract-reasoning':
        return <AbstractReasoningTest onComplete={handleTestComplete} />;
      case 'critical-thinking':
        return <CriticalThinkingTest onComplete={handleTestComplete} />;
      case 'creative-thinking':
        return <CreativeThinkingTest onComplete={handleTestComplete} />;
      case 'word-association':
        return <WordAssociationTest onComplete={handleTestComplete} />;
      case 'audio-memory':
        return <AudioMemoryTest onComplete={handleTestComplete} />;
      case 'sequence-reasoning':
        return <SequenceReasoningTest onComplete={handleTestComplete} />;
      case 'emotion-recognition':
        return <EmotionRecognitionTest onComplete={handleTestComplete} />;
      case 'multitask':
        return <MultitaskTest onComplete={handleTestComplete} />;
      case 'reading-comprehension':
        return <ReadingComprehensionTest onComplete={handleTestComplete} />;
      case 'cognitive-flexibility':
        return <CognitiveFlexibilityTest onComplete={handleTestComplete} />;
      case 'inhibitory-control':
        return <InhibitoryControlTest onComplete={handleTestComplete} />;
      case 'processing-speed':
        return <ProcessingSpeedTest onComplete={handleTestComplete} />;
      case 'spatial-memory':
        return <SpatialMemoryTest onComplete={handleTestComplete} />;
      case 'verbal-fluency':
        return <VerbalFluencyTest onComplete={handleTestComplete} />;
      case 'decision-making':
        return <DecisionMakingTest onComplete={handleTestComplete} />;
      case 'time-perception':
        return <TimePerceptionTest onComplete={handleTestComplete} />;
      case 'digit-memory':
        return <DigitMemoryTest onComplete={handleTestComplete} />;
      case 'concept-formation':
        return <ConceptFormationTest onComplete={handleTestComplete} />;
      case 'ai-battle':
        return <AIBattleMode 
          onComplete={handleTestComplete} 
          onBack={() => {
            setCurrentView('home');
            setActiveTab('ai-battle');
          }}
        />;
      case 'dashboard':
        return <Dashboard 
          testResults={testResults} 
          userProfile={userProfile} 
          achievements={achievements}
          onStartTest={handleStartTest}
        />;
      case 'profile':
        return <ProfilePage 
          userProfile={userProfile} 
          testResults={testResults}
          achievements={achievements}
          onUpdateProfile={setUserProfile}
        />;
      default:
        return null;
    }
  };

  if (currentView === 'home') {
    return (
      <HomePage
        testResults={testResults}
        userProfile={userProfile}
        achievements={achievements}
        onStartTest={handleStartTest}
        activeTab={activeTab}
        onTabChange={setActiveTab}
      />
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/50 to-indigo-50">
      <header className="border-b bg-white/70 backdrop-blur-xl sticky top-0 z-50 shadow-sm">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between min-h-[40px]">
            <div className="flex items-center gap-4">
              <motion.div
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                className="flex items-center"
              >
                <Button 
                  variant="ghost" 
                  size="sm"
                  onClick={() => {
                    setCurrentView('home');
                    setActiveTab('tests');
                  }}
                  className="flex items-center gap-2 h-8 px-3 hover:bg-blue-50 hover:text-blue-700 transition-all duration-200"
                >
                  <Home className="w-4 h-4 flex-shrink-0" />
                  <span className="leading-none">{t('nav.home')}</span>
                </Button>
              </motion.div>
              <div className="h-5 w-px bg-slate-200 flex-shrink-0" />
              <h1 className="text-lg font-semibold bg-gradient-to-r from-slate-700 to-slate-900 bg-clip-text text-transparent leading-none flex items-center">
                {currentView === 'dashboard' ? t('nav.dashboard') :
                 currentView === 'profile' ? t('nav.profile') :
                 currentView === 'ai-battle' ? t('nav.ai_battle_mode') :
                 tests.find(t => t.id === currentView)?.title}
              </h1>
            </div>
            <div className="flex items-center gap-3">
              <LanguageSelector />
              <motion.div
                whileHover={{ scale: 1.05 }}
                transition={{ duration: 0.2 }}
                className="flex items-center"
              >
                <Badge variant="secondary" className="flex items-center gap-1.5 h-8 px-3 bg-gradient-to-r from-orange-100 to-red-100 text-orange-700 border-orange-200 hover:shadow-sm transition-all duration-200">
                  <Flame className="w-3 h-3 flex-shrink-0" />
                  <span className="leading-none whitespace-nowrap">{calculateStreakDays(testResults)} {t('header.streak_days')}</span>
                </Badge>
              </motion.div>
              <motion.div
                whileHover={{ scale: 1.05 }}
                transition={{ duration: 0.2 }}
                className="flex items-center"
              >
                <Badge variant="outline" className="flex items-center gap-1.5 h-8 px-3 bg-gradient-to-r from-purple-50 to-indigo-50 text-purple-700 border-purple-200 hover:shadow-sm transition-all duration-200">
                  <Star className="w-3 h-3 flex-shrink-0" />
                  <span className="leading-none whitespace-nowrap">{t('sidebar.level')} {userProfile.level}</span>
                </Badge>
              </motion.div>
            </div>
          </div>
        </div>
      </header>
      
      <main className="container mx-auto px-4 py-6">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, ease: "easeOut" }}
        >
          {renderTestComponent()}
        </motion.div>
      </main>
    </div>
  );
}

export default function App() {
  return (
    <LanguageProvider>
      <AppContent />
    </LanguageProvider>
  );
}